<?php


namespace App\Http\service;


use App\Engine\TokenService;
use App\Exceptions\ApiException;
use App\Models\Manage;
use App\Models\Sys;
use Illuminate\Support\Facades\DB;
use App\Models\User as UserModel;

class AuthService
{
    private $manageTable="manages";
    private $model;

    public static function dy_login($data,$invite_uid="")
    {
        $user=UserModel::where("openid",$data["openid"])->first();
        if (!$user){
            $create=[
                "openid"=>$data["openid"],
                "session_key"=>$data["session_key"],
                "login_time"=>time(),
                "points"=>0,
                "egg"=>0,
                "draw_times"=>0,
                "food"=>0,
                "balance"=>0,
                "tree"=>0,
                "coupon"=>0,
                "platform"=>"dy",
                "invite_uid"=>$invite_uid
            ];
            $user=UserModel::create($create);
        }
        $cache=[
            "uid"=>$user["id"],
            "session_key"=>$data["session_key"]
        ];
        $token=(new TokenService())->saveCache($cache);
        return ["token"=>$token];
    }

    /**修改密码
     * @param $data
     */
    public function setPassword($data)
    {
        if ($data["n_password"]!=$data["r_password"])
            throw new ApiException("两次输入的密码不一致");
        $manage=new Manage();
        $res=$manage->where(["id"=>TokenService::getCurrentAid()])->first();
        if ($res["password"]!=md5($data["o_password"]))
            throw new ApiException("旧密码错误");
        return $manage->where("id",TokenService::getCurrentAid())->update(["password"=>md5($data["n_password"])]);
    }

    /**cms登录
     * @param $data
     * @return array
     * @throws ApiException
     */
    public function cmsLogin($data)
    {
        $this->model=(new ModelService($this->manageTable))->getModel();
        $data=$this->model->filter_data($data);
        $data["password"]=md5($data["password"]);
        $this->check_cms($data);
        $res=$this->model->where($data)->first();
        if (!$res)
            throw new ApiException("账号或密码错误");
        $cache=[
            "aid"=>$res["id"]
        ];
        $token=(new TokenService())->saveCache($cache);
        (new QueueService())->ManageLoginQueue($res);
        return ["token"=>$token];
    }

    private function check_cms($data)
    {
        $count=DB::table($this->manageTable)->count();
        if($count==0){
            $this->model->create($data);
        }
    }

    public function check_opcode($code)
    {
        $opcode=Sys::getValue("opcode");
        if ($code!=$opcode)
            throw new ApiException("操作码错误");
    }
}
